<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>注册</title>
  <script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/jquery"></script>
  <script src="__PUBLIC__/script/common.js" common-data-1="{:U('Mix/dest')}"></script>
  <script src="__PUBLIC__/script/jquery-weui/dist/js/jquery-weui.min.js"></script>
  <script src="__PUBLIC__/script/jquery-weui/dist/js/city-picker.min.js"></script>
  <!-- <script src="__PUBLIC__/script/mockjs/dist/mock-min.js"></script> -->
  <!-- <script src="__PUBLIC__/script/pub/fake.js"></script> -->
  <link rel="stylesheet" href="__PUBLIC__/script/jquery-weui/dist/lib/weui.min.css">
  <link rel="stylesheet" href="__PUBLIC__/script/jquery-weui/dist/css/jquery-weui.min.css">
  <link rel="stylesheet" href="__PUBLIC__/styles/base.css">
  <link rel="stylesheet" href="__PUBLIC__/styles/signup.css">
  <style>
    pre{display:none;}
  </style>
</head>
<body>
  <div style='display:none;' id='displayNone'>
    <input type="hidden" name="获取短信验证码" id='url_getCode' value="{:U('Home/index/sms')}" form='not_submit'>
    <!-- <input type="hidden" name="获取渠道列表" id='getQudaoURL' value="{:U('Wchat/get_qudao_list')}"> -->
    <input type="hidden" name="验证手机是否重复" id='re_ck_phone' value="{:U('Home/index/re_ck_phone')}">
  </div>
  <div class="container" style="min-height:calc(100vh - 2rem - 2vh);">
    <div class="logo" style="width:70%;min-width:200px;margin:auto;">
      <img src="__PUBLIC__/res/logo.png" alt="logo" style='width:100%;'>
    </div>
    <div style='display:none;'>
    </div>
    <div class="signup">
      <form autocomplete="off" action="{:U('Mix/post_from_frg')}" method="post" id = 'signUp'>
        <div class="tel_box">
          <input type="tel" autocomplete="off" name="web_phone" id="web_phone" placeholder="手机号码"><button id='getCode'>获取验证码</button>
        </div>
        <input type="text" autocomplete="off" form='not_submit' name="web_yanzheng_code" id="signup_yanzheng_code" placeholder="请输入验证码"><br>
        <input type="password" autocomplete="off" name="web_pass" id="signup_yaoqin" placeholder="输入新密码"><br>
        <input type="submit" id = "sign_submit" value="重置密码">
      </form>
    </div>
  </div>
  <div class="bottomMess"><span><a href="{:U('Wchat/login')}">返回登陆</a></span></div>
  <script>
    $(document).ready(() => {
      $('#getCode').one({'click': sendCode}, {id: 'getCode', urlID: 'url_getCode', phoneID: 'web_phone'})

      $('#sign_submit').on('click', function post (evt) {
        evt.preventDefault()
        // 判断验证码是否填写正确
        const yanzheng_code = sessionStorage.getItem(`yanzheng_code`)
        if (yanzheng_code !== `${String($('#signup_yanzheng_code').val())}`) {
          $.toptip(`验证码填写错误，请检查`, 'error')
          throw new Error(`验证码填写错误`)
        }
        // 判断密码
        if($('#signup_yaoqin').val() === '' || $('#signup_yaoqin').val().length < 8) {
          $.toptip('请填写8位以上密码！', 'error')
          throw new Error(`请填写8位以上密码！`)
        }
        $('#signUp').attr('action', url).submit()
      })
    })
  </script>

  <!-- 验证码相关，包括倒数，gen随机密码，发送密码 -->
  <script>
    function changeCountDownNum (id, num, fn, placeholder) {
      if (num >= 0) {
        $(`#${id}`).text(num--)
        return setTimeout(fn, 1000, id, num, changeCountDownNum, placeholder)
      } else {
        $(`#${id}`).text(placeholder)
        $('#getCode').one({'click': sendCode}, {id: 'getCode', urlID: 'url_getCode', phoneID: 'web_phone'})
        return null
      }
    }
    // gen一个随机数值串出来
    function genRandCode (leng) {
      if( String(typeof leng).toLocaleLowerCase() === 'number') return Math.random().toFixed(leng).toString().replace(/\d\./, '')
      else {
        $('#getCode').one({'click': sendCode}, {id: 'getCode', urlID: 'url_getCode', phoneID: 'web_phone'})
        throw new Error(`收到类型不为数值的参数：${leng} | ${String(typeof leng).toLocaleLowerCase()}。无法产生指定长度随机数`)
      }
    }
    function sendCode (evt) {
      evt.preventDefault()

      // 正则，暂时没用上
      const isChinaMobile = /^134[0-8]\d{7}$|^(?:13[5-9]|147|15[0-27-9]|178|18[2-478])\d{8}$/; //移动方面最新答复
      const isChinaUnion = /^(?:13[0-2]|145|15[56]|176|18[56])\d{8}$/; //向联通微博确认并未回复
      const isChinaTelcom = /^(?:133|153|177|18[019])\d{8}$/; //1349号段 电信方面没给出答复，视作不存在
      const isOtherTelphone  = /^170([059])\d{7}$/;//其他运营商

      const phoneValue = $(`#${evt.data.phoneID}`).val().replace(/\s/g,'')
      const send_code = genRandCode(8)
      if (phoneValue.length !== 11 || (!isChinaMobile.test(phoneValue) && !isChinaUnion.test(phoneValue) && !isChinaTelcom.test(phoneValue) && !isOtherTelphone.test(phoneValue))) {
        $.toptip('请输入有效中国大陆手机号', 'error')
        $('#getCode').one({'click': sendCode}, {id: 'getCode', urlID: 'url_getCode', phoneID: 'web_phone'})
        throw new Error(`手机号码判断为误：${phoneValue}`)
      } else {
        // 验证手机号码是否重复
        const checkURL = String($('#re_ck_phone').val())
        const ajaxData = {
          phone: phoneValue
        }
        $.ajax(checkURL, {
          method: 'post',
          data: ajaxData,
          async: false
        }).fail((err) => {
          event.preventDefault()
          $.toptip('检查手机号时网络通信失败','error')
          $('#getCode').off('click')
          $('#getCode').one({'click': sendCode}, {id: evt.data.id, urlID: evt.data.urlID, phoneID: evt.data.phoneID})
          throw err
        }).done((res) => {
          if (res.code && String(res.code) === '2') {
            $.toptip('手机号存在，正在发送验证码','success')
          } else if (res.code && String(res.code) === '1') {
            event.preventDefault()
            $.toptip('手机号未注册','warning')
            $('#getCode').off('click')
            $('#getCode').one({'click': sendCode}, {id: evt.data.id, urlID: evt.data.urlID, phoneID: evt.data.phoneID})
            throw new Error(`手机号未注册`)
          } else {
            event.preventDefault()
            $.toptip('未知返回, 查看控制台得到更多消息','error')
            console.log(`验证手机时服务器返回：${res}`)
            $('#getCode').off('click')
            $('#getCode').one({'click': sendCode}, {id: evt.data.id, urlID: evt.data.urlID, phoneID: evt.data.phoneID})
            throw new Error(`验证手机时服务器返回错误`)
          }
        })
      }
      const smsURL = $(`#${evt.data.urlID}`).val()
      let timer = ''
      $(`#${evt.data.id}`).on('click', function CountDown(event) {
        event.preventDefault();
        $.toptip('请稍候')
      })
      // 处理页面样式
      timer = changeCountDownNum(evt.data.id, 60, changeCountDownNum, '获取验证码')
      debugger
      $.ajax(smsURL, {
        method: 'post',
        data: {mobile: phoneValue, send_code: send_code}
      }).done((data) => {
        //array(
        // code:短信通知返回码
        // msg:短信验证码信息
        // id:存储验证码id
        // send_code:验证码
        //)
        if (String(data.send_code) !== `${send_code}` || String(data.code) !== '2') {
          // 重置状态
          clearTimeout(timer)
          $(`#${evt.data.id}`).text('获取验证码')
          $('#getCode').off('click')
          $('#getCode').one({'click': sendCode}, {id: evt.data.id, urlID: evt.data.urlID, phoneID: evt.data.phoneID})
          throw new Error(`请求发生错误, 服务器返回: 3${data.msg}`)
        } else {
          sessionStorage.clear()
          sessionStorage.setItem(`yanzheng_code`, `${data.send_code}`)
        }
      }).fail((err) => {
        console.dir(err)
        // 重置状态
        clearTimeout(timer)
        $(`#${evt.data.id}`).text('获取验证码')
        $('#getCode').off('click')
        $('#getCode').one({'click': sendCode}, {id: evt.data.id, urlID: evt.data.urlID, phoneID: evt.data.phoneID})
        throw new Error(`请求发生错误`)
      })
    }
  </script>
</body>
</html>